﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using HU8.Helpers.Files;
using HU8.Helpers.Base;

namespace HU8.Web.FileExplorer.FileExplorer.WebServices
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : IHttpHandler {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                FileExplorerConfig config = new FileExplorerConfig(context.Server);

                string path = context.Request["path"].ToString();
                path = Microsoft.JScript.GlobalObject.decodeURI(path);
                if (string.IsNullOrEmpty(path))
                {
                    path = "~/";
                }
                path = path.Replace("~/", config.BasePath);

                int chunk = context.Request["chunk"] != null ? int.Parse(context.Request["chunk"]) : 0;
                int chunks = context.Request["chunks"] != null ? int.Parse(context.Request["chunks"]) : 0;
                string fileName = context.Request["name"] != null ? context.Request["name"] : string.Empty;

                HttpPostedFile fileUpload = context.Request.Files[0];
                var uploadPath = context.Server.MapPath(path);
                //if (chunk == 0)
                //{
                //    fileName = FileHelper.FixFileName(uploadPath, fileName);
                //}
                using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    var buffer = new byte[fileUpload.InputStream.Length];
                    fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                }
                //如果正确继续执行，错误则抛出异常
                context.Response.ContentType = "text/plain";
                context.Response.Write("{\"jsonrpc\" : \"2.0\", \"result\" : \"上传成功\", \"id\" : \"id\"}");
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 102, \"message\":" + ex.Message + "\"}, \"id\" : \"id\"}");
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}